package cn.miw.android.bdmp3.service;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import cn.miw.android.bdmp3.MainActivity;
import cn.miw.android.bdmp3.R;
import cn.miw.android.bdmp3.model.ASong;
import cn.miw.android.bdmp3.model.BaiDuListItem;

public class MusicService extends Service {
	private List<BaiDuListItem> songs = null;
	private MediaPlayer mMediaPlayer;
	private NotificationManager nm;
	private WakeLock mWakeLock;
	private MyPhoneCallListener myPhoneCallListener;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			String incomingNumber = (String) msg.obj;
			if (mMediaPlayer != null)
				try {
					switch (msg.what) {
					case TelephonyManager.CALL_STATE_OFFHOOK:
						//摘机
					case TelephonyManager.CALL_STATE_RINGING:
						// 振铃
						if (mMediaPlayer.isPlaying())
							mMediaPlayer.pause();
						break;
					case TelephonyManager.CALL_STATE_IDLE:
						// 挂机
						mMediaPlayer.start();
						break;

					default:
						break;
					}
				} catch (Exception e) {
					System.out.println(incomingNumber);
				}
			super.handleMessage(msg);
		}
	};

	private OnCompletionListener listener = new OnCompletionListener() {

		public void onCompletion(MediaPlayer mp) {
			if (songs != null) {
				next();
			} else {
				nm.cancel(824);
			}
		}
	};

	private OnErrorListener errListener = new OnErrorListener() {

		public boolean onError(MediaPlayer mp, int what, int extra) {
			mp.reset();
			return false;
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	private void init() {
		if (songs != null && songs.size() > Pub.curPos)
			try {
				BaiDuListItem item = songs.get(Pub.curPos);
				Pub.curSongName = item.getSong() + "-" + item.getSinger();
				showNotification(R.drawable.icon_play, item.getSong(), "百度音乐播放器", Pub.curSongName);
				if (mMediaPlayer == null) {
					initPlayer();
				}
				if (item != null) {
					mMediaPlayer.reset();
					mMediaPlayer.setDataSource(item.getId());
					mMediaPlayer.prepare();
					mMediaPlayer.start();
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}

	@Override
	public void onCreate() {
		super.onCreate();
		monitorCallState();
		addWakeLock();
		initPlayer();
		songs = Pub.localMusics;
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	}

	private void initPlayer() {
		Pub.mediaPlayer = new MediaPlayer();
		mMediaPlayer = Pub.mediaPlayer;
		mMediaPlayer.setOnCompletionListener(listener);
		mMediaPlayer.setOnErrorListener(errListener);
	}

	private void monitorCallState() {
		myPhoneCallListener = new MyPhoneCallListener(handler);
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		tm.listen(myPhoneCallListener, PhoneStateListener.LISTEN_CALL_STATE);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		String action = intent.getAction();
		if (action.equals(Pub.PLAY_ACTION)) {
			play();
		} else if (action.equals(Pub.PAUSE_ACTION)) {
			pause();
		} else if (action.equals(Pub.NEXT_ACTION)) {
			next();
		} else if (action.equals(Pub.PREVIOUS_ACTION)) {
			previous();
		} else if (action.equals(Pub.TRY_ACTION)) {
			BaiDuListItem item = (BaiDuListItem) intent.getSerializableExtra("item");
			tryMusic(item);
		}
	}

	private void tryMusic(BaiDuListItem item) {
		try {
			Pub.curSongName = "试听：" + item.getSong() + "-" + item.getSinger();
			showNotification(R.drawable.icon_play, item.getSong(), "百度音乐播放器", Pub.curSongName);
			ASong aSong = Util.getASong(item);
			String url = "";
			if (aSong != null)
				if (aSong.getUrls() != null)
					if (aSong.getUrls().get(0) != null) {
						url = aSong.getUrls().get(0).getTrueURL();
					}

			if (url != "") {
				mMediaPlayer.reset();
				mMediaPlayer.setDataSource(url);
				mMediaPlayer.prepare();
				mMediaPlayer.start();
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void play() {
		try {
			if (Pub.PlayMode[Pub.curMode] == R.drawable.mode_repeaterandom) {
				Pub.curPos = genRandom();
			}
			if (Pub.curPos >= songs.size()) {
				Pub.curPos = 0;
			}
			init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void showNotification(int icon, String tickertext, String title, String content) {
		// 设置一个唯一的ID，随便设置
		// Notification管理器
		Notification notification = new Notification(icon, tickertext, System.currentTimeMillis());
		// 后面的参数分别是显示在顶部通知栏的小图标，小图标旁的文字（短暂显示，自动消失）系统当前时间（不明白这个有什么用）
		notification.defaults = Notification.DEFAULT_LIGHTS;
		// 这是设置通知是否同时播放声音或振动，声音为Notification.DEFAULT_SOUND
		// 振动为Notification.DEFAULT_VIBRATE;
		// Light为Notification.DEFAULT_LIGHTS，在我的Milestone上好像没什么反应
		// 全部为Notification.DEFAULT_ALL
		// 如果是振动或者全部，必须在AndroidManifest.xml加入振动权限
		PendingIntent pt = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
		// 点击通知后的动作，这里是转回main 这个Acticity
		notification.setLatestEventInfo(this, title, content, pt);
		nm.notify(824, notification);
	}

	private void pause() {
		stopSelf();
		nm.cancel(824);
	}

	private void previous() {
		try {
			Pub.curPos--;
			if (Pub.PlayMode[Pub.curMode] == R.drawable.mode_repeaterandom) {
				Pub.curPos = genRandom();
			}
			if (Pub.curPos < 0) {
				Pub.curPos = songs.size() - 1;
			}
			init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void next() {
		try {
			Pub.curPos++;
			if (Pub.PlayMode[Pub.curMode] == R.drawable.mode_repeaterandom) {
				Pub.curPos = genRandom();
			}
			if (Pub.curPos >= songs.size()) {
				Pub.curPos = 0;
			}
			init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void addWakeLock() {
		try {
			PowerManager pm;
			pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
			mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "百度音乐");
			mWakeLock.acquire();
			mWakeLock.setReferenceCounted(false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 服务结束时要释放MediaPlayer
	@Override
	public void onDestroy() {
		try {
			Pub.mediaPlayer.release();
			Pub.mediaPlayer = null;
			mMediaPlayer = null;
			if (mWakeLock != null) {
				mWakeLock.release();
				mWakeLock = null;
			}
			nm.cancel(824);
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	private int genRandom() {
		int x = 0;
		try {
			Random rdm = new Random(System.currentTimeMillis());
			x = Math.abs(rdm.nextInt()) % Pub.localMusics.size();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return x;
	}
}
